package com.codeZ.SingletonPattern.destroySingleton;

import java.io.*;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

/**
 * @Author code_zhang
 * @Date 2024/6/15 17:48
 * 序列化对于单例的破坏
 *
 *
 *
 */
public class SerializationDestroySingleton {
    public static void main(String[] args) throws Exception {
        Path path = Paths.get("tempFile.obj");
        ObjectOutputStream oos = new ObjectOutputStream(Files.newOutputStream(path));
        oos.writeObject(SingletonPattern02.getInstance());
        ObjectInputStream ois = new ObjectInputStream(Files.newInputStream(path));
        SingletonPattern02 instance = (SingletonPattern02) ois.readObject();
        System.out.println(instance);
        System.out.println(instance == SingletonPattern02.getInstance());
    }
}

class SingletonPattern02 implements Serializable {
    private SingletonPattern02() {
    }

    private static class SingletonPattern01Holder {
        private static final SingletonPattern02 INSTANCE = new SingletonPattern02();
    }

    public static SingletonPattern02 getInstance() {
        return SingletonPattern01Holder.INSTANCE;
    }

    /**
     * 解决办法 ：重写readResolve方法
     * 只需要在单例类中定义eadResolve方法，就可以解决序列化对于单例的破坏
     * 程序会判断是否有readResolve.方法，如加果有就执行该方法 不存在就创建新的对象(反射)
     * @return
     */
//    private Object readResolve() {
//        return SingletonPattern01Holder.INSTANCE;
//    }
}